package com.xc.common.tool;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.List;
import java.util.Map;

@Component
public class WordUtils {
    public static void addPictureToRun(XWPFRun run, String blipId, int id, int width, int height){
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;

        CTInline inline =run.getCTR().addNewDrawing().addNewInline();

        String picXml = "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
        "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +

        "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
        "         <pic:nvPicPr>" +
                "            <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
                "            <pic:cNvPicPr/>" +
                "         </pic:nvPicPr>" +
                "         <pic:blipFill>" +
                "            <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
                "            <a:stretch>" +
                "               <a:fillRect/>" +
                "            </a:stretch>" +
                "         </pic:blipFill>" +
                "         <pic:spPr>" +
                "            <a:xfrm>" +
                "               <a:off x=\"0\" y=\"0\"/>" +
                "               <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
                "            </a:xfrm>" +
                "            <a:prstGeom prst=\"rect\">" +
                "               <a:avLst/>" +
                "            </a:prstGeom>" +
                "         </pic:spPr>" +
                "      </pic:pic>" +
                "   </a:graphicData>" +
                "</a:graphic>";

        //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        try {
                xmlToken = XmlToken.Factory.parse(picXml);
        } catch(XmlException xe) {
                xe.printStackTrace();
        }
        inline.set(xmlToken);
        //graphicData.set(xmlToken);

        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(width);
        extent.setCy(height);

        CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        docPr.setId(id);
        docPr.setName("Picture " + id);
        docPr.setDescr("Generated");
    }

    /*
        创建FileItem
         */
    public FileItem createFileItem(File file, String fieldName) {
            FileItemFactory factory = new DiskFileItemFactory(16, null);


        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
                e.printStackTrace();
        }
        return item;
    }
    public static void closeStream(InputStream inStream) {
        try {
                inStream.close();
        } catch (IOException e) {
                e.printStackTrace();
        }
    }
    public static void writer(XWPFDocument doc, String outSrc, Map<String,Object> map) {

        /**
         * 替换段落中指定的文本
         */
        for(XWPFParagraph p : doc.getParagraphs()){
                List<XWPFRun> runs = p.getRuns();
            if(runs != null){
                for(XWPFRun r : runs){
                        //需要替换的文本
                        String text = r.getText(0);
                    //替换指定的文本
                    for(String key : map.keySet()){
                        if(text != null && text.equals(key)){
                                //替换的时候要注意，setText是有两个参数的
                                //第一个是替换的文本，第二个是从哪里开始替换
                                //0是替换全部，如果不设置那么默认就是从原文字
                                //结尾开始追加
                                r.setText((String)map.get(key),0);
                        }
                    }
                }
            }
        }
        /**
         * 替换表格中指定的文字
         */
        for(XWPFTable tab : doc.getTables()){
            for(XWPFTableRow row : tab.getRows()){
                for(XWPFTableCell cell : row.getTableCells()){
                    //注意，getParagraphs一定不能漏掉
                    //因为一个表格里面可能会有多个需要替换的文字
                    //如果没有这个步骤那么文字会替换不了
                    for(XWPFParagraph p : cell.getParagraphs()){
                        for(XWPFRun r : p.getRuns()){
                                String text = r.getText(0);
                            for(String key : map.keySet()){
                                if(text!=null){
                                    if(text.equals(key)){
                                            r.setText((String)map.get(text),0);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


}